/**
 * 准备函数
 */
var operateRight = new Object();
var cNewsDetailEditor;
var mNewsDetailEditor;
$(document).ready(function() {
	
	// 加载权限
	loadRight();
	
	// 加载表格
	queryNews();
	
	// 绑定函数
	$("#queryNewsButton").bind("click", confirmQueryNews);
	$("#createNewsButton").bind("click", showCreateNewsDialog);
	$("#confirmCreateNewsButton").bind("click", confirmCreateNews);
	$("#confirmModifyNewsButton").bind("click", confirmModifyNews);
	
	// 加载form模块
	layui.use(['form','laydate'], function() {
		$form = layui.form;
		laydate = layui.laydate;
		laydate.render({
			elem : '#cPushTime',
			istoday : true,
			format : Global.DATE_FORMAT_STR
		});
		laydate.render({
			elem : '#mPushTime',
			istoday : true,
			format : Global.DATE_FORMAT_STR
		});
	})
	
	//绑定下载提示框
	//$('a[rel*=downloadr]').downloadr();
});

/**
 * 加载权限
 */
function loadRight() {
	operateRight.modifyRight = $("#modify").val();
	operateRight.deleteRight = $("#delete").val();
	operateRight.publishRight = $("#publish").val();
}

/**
 * 查询
 */
function queryNews(pageIndex, pageSize) {
	// 组装参数
	var data = {};
	var title = $('#title').val();
	if (Utils.isNotNull(title)) {
		data['title'] = title;
	}
	
	var categoryId = $('#categoryId').val();
	if (Utils.isNotNull(categoryId)) {
		data['categoryId'] = categoryId;
	}
	
	var isPush = $('#isPush').val();
	if (Utils.isNotNull(isPush)) {
		data['isPush'] = isPush;
	}
	
	// 设置分页参数
	setPageIndex(data, pageIndex, pageSize);
	
	// 调用接口 
	var response = callInterface("post", "home/queryArticle", data, false);
	if (response.code == 0) {
		var count = 0;
		if( Utils.isNotNull(response.data) && Utils.isNotNull(response.data.totalCount) ){
			count = response.data.totalCount;
		}
		
		// 清空表格及分页
		$("#dataTable tr:not(:first)").remove();
		$("#pageDiv").html("");

		// 动态添加一行
		if (count == 0) {
			var cols = $("#dataTable").find("tr:first th");
			$('#dataTable').append("<tr><td colspan='" + cols.length + "'>无数据!</td></tr>");
			return false;
		}

		var list = response.data.list;
		if (list != null && list.length > 0) {
			var num =0;
			for ( var i in list) {
				var trHtml = "<tr>";
				trHtml += "<td align='center'>" + list[i].sort + "</td>";
				trHtml += "<td>" + cutString(list[i].title, 30) + "</td>";
				trHtml += "<td align='center'>" + list[i].categoryName + "</td>";
				trHtml += "<td>" + cutString(list[i].abstractContent, 50) + "</td>";
				var pushText = list[i].isPush?'是':'否';
				trHtml += "<td align='center'>" + pushText + "</td>";
				trHtml += "<td align='center'>" + list[i].pushTime + "</td>";
				trHtml += "<td align='center'>" + list[i].createdTime + "</td>";
				trHtml += "<td align='center'>";
				// 操作
				if (operateRight.modifyRight == 1) {
					trHtml += '<a href="javascript:void(0);" class="edit" onclick="showModifyNewsDialog(\''
						+ list[i].id
						+ '\');">编辑</a> ';
				}
				if (operateRight.deleteRight == 1) {
					trHtml += '<a href="javascript:void(0);" class="delete" onclick="deleteNews(\''
							+ list[i].id
							+ '\');">删除</a> ';
				}
				if (operateRight.publishRight == 1 && !list[i].isPush) {
					trHtml += '<a href="javascript:void(0);" class="copy" onclick="publishNews(\''
							+ list[i].id
							+ '\');">发布</a>';
				} 
				trHtml += "</td>";
				trHtml += "</tr>";

				// 动态添加一行
				$('#dataTable').append(trHtml);
			}
		}
		
		// 调用分页
		layui.use(['laypage'], function() {
			var laypage = layui.laypage;
			laypage.render({
				elem : 'pageDiv',
				// pages : pages,
				curr : pageIndex || 1, // 当前页
				count : count,
				limit : pageSize, 
				skip : true, // 是否开启跳页
				layout : ['count', 'prev', 'page', 'next', 'limit', 'skip'],
				groups : 5, // 连续显示分页数
				jump : function(obj, first) {  
					if (!first) {
						queryNews(obj.curr, obj.limit);
					}
				}
			});
		});
	}
}

/**
 * 确认查询
 */
function confirmQueryNews() {
	queryNews();
}

/**
 * 设置是否隐藏
 */
function publishNews($id) {
	// 获取参数
	var data = {};
	data['id'] = $id;
	data['isPush'] = 1;

	// 调用接口
	var response = callInterface("post", "home/modifyArticlePush", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');
		
		// 刷新
		queryNews(currPage);
	}
	else {
		showErrorMsg(response.code, response.message);
	}
	return false;
}

/**
 * 显示创建对话框
 */
function showCreateNewsDialog() {
	$("#createNewsDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#addNewsForm')[0].reset();
	$("#cNewsType").val(" ");
	$("#cNewsImgUrl").val('');
	$("#cNewsImgFileDiv").html('');
	
	$form.render();
	
	//创建editor
	cNewsDetailEditor = undefined;
	var E = window.wangEditor;
    cNewsDetailEditor = new E('#cNewsDetail');
    cNewsDetailEditor.customConfig.customUploadImg = function (files, insert) {
    	//自定义的上传图片到服务器方法 
        uploadEditorImage(files,insert);
    }
    cNewsDetailEditor.create();
    cNewsDetailEditor.txt.clear();
}

/**
 * 确认创建
 */
function confirmCreateNews() {
	// 获取参数
	var data = {};
	var sort = $.trim($('#cNewsSort').val());
	if (sort == '') {
		showAlert('新闻排序不能为空!');
		return false;
	}
	data['sort'] = sort;
	
	var title = $.trim($('#cNewsTitle').val());
	if (title == '') {
		showAlert('新闻标题不能为空!');
		return false;
	}
	data['title'] = title;
	
	var pushTime = $.trim($('#cPushTime').val());
	if (pushTime == '') {
		showAlert('新闻发布时间不能为空!');
		return false;
	}
	data['pushTime'] = pushTime;
	
	var description = $.trim($('#cNewsDesc').val());
	if (description != '') {
		data['description'] = description;
	}
	
	var keyWords = $.trim($('#cKeyWords').val());
	if (keyWords != '') {
		data['keyWords'] = keyWords;
	}
	
	var content = $.trim($('#cNewsContent').val());
	if (content == '') {
		showAlert('新闻摘要不能为空!');
		return false;
	}
	data['abstractContent'] = content;
	
	var imgUrl = $.trim($('#cNewsImgUrl').val());
	if (imgUrl == '') {
		showAlert('请上传新闻图片!');
		return false;
	}
	data['titlePic'] = imgUrl;
	
	var typeId = $.trim($('#cNewsType').val());
	if (typeId == '') {
		showAlert('请选择新闻类型!');
		return false;
	}
	data['categoryId'] = typeId;
	
	var ehtml = $.trim(cNewsDetailEditor.txt.html());
	if( ehtml == "<p><br></p>" ){
		showAlert('新闻详情不能为空!');
		return false;
	}
	data['content'] = ehtml;
	
	data['isPush'] = 0;
	
	// 调用接口
	var response = callInterface("post", "home/createArticle", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');

		// 关闭对话框
		$('#createNewsDialog').modal("hide");

		// 刷新
		queryNews();
	} else {
		showErrorMsg(response.code, response.message);
	}

	return false;
}

/**
 * 显示修改对话框
 */
function showModifyNewsDialog(id) {
	// 显示对话框
	$("#modifyNewsDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#modifyNewsForm')[0].reset();
	
	//获取新闻详情
	getNewsDetail(id);
}

/**
 * 获取新闻详情
 * @param id
 */
function getNewsDetail(id){
	// 调用接口
	var response = callInterface("post", "home/getArticleDetail", {
		'id' : id
	}, false);
	if (response.code == 0) {
		var data = response.data;
		$("#mNewsId").val(data.id);
		$("#mNewsSort").val(data.sort);
		$("#mPushTime").val(data.pushTime);
		$("#mNewsType").val(data.categoryId);
		$("#mNewsTitle").val(data.title);
		$("#mNewsDesc").val(data.description);
		$("#mKeyWords").val(data.keyWords);
		$("#mNewsContent").val(data.abstractContent);
		$("#mNewsImgUrl").val(data.titlePic);
		$("#mNewsImgFileDiv").html(fillFileDiv(data.titlePic));
		
		$form.render();
		
		mNewsDetailEditor = undefined;
		var E = window.wangEditor;
	    mNewsDetailEditor = new E('#mNewsDetail');
	    mNewsDetailEditor.customConfig.customUploadImg = function (files, insert) {
	    	uploadEditorImage(files,insert);
	    }
	    mNewsDetailEditor.create();
	    mNewsDetailEditor.txt.html(data.content);
		
	} else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 确认修改
 * @param id
 */
function confirmModifyNews(){
	// 获取参数
	var data = {};
	data['id'] = $.trim($('#mNewsId').val());
	
	var sort = $.trim($('#mNewsSort').val());
	if (sort == '') {
		showAlert('新闻排序不能为空!');
		return false;
	}
	data['sort'] = sort;
	
	var title = $.trim($('#mNewsTitle').val());
	if (title == '') {
		showAlert('新闻标题不能为空!');
		return false;
	}
	data['title'] = title;
	
	var pushTime = $.trim($('#mPushTime').val());
	if (pushTime == '') {
		showAlert('新闻发布时间不能为空!');
		return false;
	}
	data['pushTime'] = pushTime;
	
	var description = $.trim($('#mNewsDesc').val());
	if (description != '') {
		data['description'] = description;
	}
	
	var keyWords = $.trim($('#mKeyWords').val());
	if (keyWords != '') {
		data['keyWords'] = keyWords;
	}
	
	var content = $.trim($('#mNewsContent').val());
	if (content == '') {
		showAlert('新闻摘要不能为空!');
		return false;
	}
	data['abstractContent'] = content;
	
	var imgUrl = $.trim($('#mNewsImgUrl').val());
	if (imgUrl == '') {
		showAlert('请上传新闻图片!');
		return false;
	}
	data['titlePic'] = imgUrl;
	
	var typeId = $.trim($('#mNewsType').val());
	if (typeId == '') {
		showAlert('请选择新闻类型!');
		return false;
	}
	data['categoryId'] = typeId;
	
	var ehtml = $.trim(mNewsDetailEditor.txt.html());
	if( ehtml == "<p><br></p>" ){
		showAlert('新闻详情不能为空!');
		return false;
	}
	data['content'] = ehtml;
	
	data['isPush'] = 0;
	
	// 调用接口
	var response = callInterface("post", "home/modifyArticle", data,
			false);
	if (response.code == 0) {
		showMsg('操作成功!');

		// 关闭对话框
		$('#modifyNewsDialog').modal("hide");

		// 刷新
		queryNews(currPage);
	} else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 删除新闻
 * @param id
 */
function deleteNews(id){
	// 设置参数
	var data = {
		"id" : id
	};
	
	// 询问框
	layer.confirm('确定删除该新闻吗？', {
		offset:'20px',
	  btn: ['确定','取消'] //按钮
	}, function(index){
		// 调用接口
		var response = callInterface("post", "home/delArticle",
				data, false);
		if (response.code == 0) {
			showMsg('操作成功!');
			
			layer.close(index);
			// 刷新
			queryNews(currPage);
		} else {
			showErrorMsg(response.code, response.message);
		}
	}, function(){
		return;
	});
}


/**
 * 上传图片并预览 
 * $imageUrlFile:图片文件 
 * $imageShowDiv:图片预览 
 * $imageUrlId:图片UrlID
 * $fileType:文件类型(0:其他文件; 1:用户头像; 2:设备; 3:广告素材; 4：数据报告; 5:公司资料; 6:效果监播)
 */
function showUploadFile($imageUrlFile, $imageShowDiv, $imageUrlId, $fileType, isImg) {
	var fileObjs = document.getElementById($imageUrlFile);
	var fileList = fileObjs.files;
	for (var i = 0; i < fileList.length; i++) {
		if(isImg){
			if (!/\.(gif|jpg|jpeg|png|bmp)$/.test(fileList[i].name.toLowerCase())) {
				$("#" + $imageUrlFile).tips({
					side : 3,
					msg : '图片类型必须是gif、jpeg、jpg、png、bmp格式',
					bg : '#1abc9d',
					time : 5
				});
				return false;
			}
		}else{
			if (!/\.(pdf)$/.test(fileList[i].name.toLowerCase())) {
				$("#" + $imageUrlFile).tips({
					side : 3,
					msg : '请上传PDF格式文件',
					bg : '#1abc9d',
					time : 5
				});
				return false;
			}
		}
	}
	
	var url="";
	var html="";
	var imageShowDiv = document.getElementById($imageShowDiv);
	
	// 调用接口
	for (var i = 0; i < fileList.length; i++) {
		var formdata = new FormData();
		formdata.append("dataFile", fileList[i]);
		formdata.append("fileType", $fileType);
		$.ajax({
			type : 'POST',
			url : 'file/uploadFile',
			data : formdata,
			dataType : "json",
//			async : false,
			cache : false,
			contentType : false,// 必须false才会自动加上正确的Content-Type
			processData : false,// 必须false才会避开jQuery对formdata的默认处理,XMLHttpRequest会对 formdata进行正确的处理
			beforeSend : function() {
				//创建LoadingDiv
				createLoadingDiv();
			},
			success : function(response) {
				if (response.code == 0) {
					// showAlert("文件上传成功!");
					// 获取返回路径
					url += response.data.url+",";
					html += fillFileDiv(response.data.url);
					//html += "&nbsp;<a href='javascript:openUploadFileUrl(\""+response.data+"\");'>预览_"+fileList[i].name+"</a>&nbsp;&nbsp;";
				} else {
					showAlert(response.message);
				}
				if (url != "" && url.length > 0) {
					imageShowDiv.innerHTML = html;
					$("#" + $imageUrlId).val(url.substring(0, url.length - 1));
				}
			},
			error : function(data) {
				//关闭LoadingDiv
				closeLoadingDiv();
				showAlert(fileList[i]+"上传失败!");
			}, 
			complete : function() {
				//关闭LoadingDiv
				closeLoadingDiv();
			}
		});
	}
	return false;
}